package zjut.raymond.witdemo.ui;

import android.graphics.PointF;
import android.net.Uri;
import android.net.wifi.ScanResult;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.davemorrissey.labs.subscaleview.ImageSource;

import org.jetbrains.annotations.NotNull;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;

import cn.finalteam.okhttpfinal.BaseHttpRequestCallback;
import cn.finalteam.okhttpfinal.HttpRequest;
import cn.finalteam.okhttpfinal.RequestParams;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import zjut.raymond.witdemo.R;
import zjut.raymond.witdemo.pojo.ReferencePoint;
import zjut.raymond.witdemo.ui.view.MapView;
import zjut.raymond.witdemo.util.ApiCode;
import zjut.raymond.witdemo.util.ApiResult;
import zjut.raymond.witdemo.util.OkHttpUtil;
import zjut.raymond.witdemo.util.WifiScanUtils;
import zjut.raymond.witdemo.viewmodel.CollectorViewModel;

/**
 * A simple {@link Fragment} subclass.
 * create an instance of this fragment.
 */
public class CollectorFragment extends Fragment implements View.OnClickListener {
    private static final String TAG = "CollectorFragment";

    private final static int START_SCAN_WIFI_CMD = 1024;
    private final static int STOP_SCAN_WIFI_CMD = 1025;
    private final static int SCAN_STATUS_SUCCESS = 1026;
    private final static int SCAN_STATUS_FAILURE = 1027;
    private final static int UPLOAD_DATA_SUCCESS = 1028;
    private final static int WAITING_NEXT_SCAN = 1029;

    public static Handler sHandler;
    private static final int PAINT_MAP = 0x01;
    private WifiScanUtils collectorWifiScanUtils;
    private int id;
    private String coord;
    private CollectorViewModel viewModel;

    private TextView textViewId, textViewCoord, textViewCount, textViewResult, textViewScanStatus;
    private Button btnStartScan, btnStopScan;

    private boolean isScaning = false;

    public CollectorFragment() {
        // Required empty public constructor
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        viewModel = new ViewModelProvider(getActivity()).get(CollectorViewModel.class);
        id = getArguments().getInt("rp_id");
        coord = getArguments().getString("rp_coord");
        initView();
        initHandler();
        viewModel.getScanCount().observe(getActivity(), integer -> textViewCount.setText(integer + ""));
    }

    private void initView() {
        textViewId = getView().findViewById(R.id.tv_rp_id_detail);
        textViewCoord = getView().findViewById(R.id.tv_rp_coord_detail);
        textViewCount = getView().findViewById(R.id.tv_scan_count);
        textViewResult = getView().findViewById(R.id.tv_scan_result);
        textViewScanStatus = getView().findViewById(R.id.tv_Scan_Status);
        btnStartScan = getView().findViewById(R.id.btn_start_scan);
        btnStopScan = getView().findViewById(R.id.btn_stop_scan);
        btnStartScan.setOnClickListener(this);
        btnStopScan.setOnClickListener(this);
        textViewId.setText("参考点id: " + id);
        textViewCoord.setText("参考点坐标: " + coord);
        textViewScanStatus.setText("点击按钮开始扫描！");
        textViewCount.setText("0");
        textViewResult.setText("往下滑动查看扫描结果：");
    }

    private void initWifiScanner() {
        collectorWifiScanUtils = new WifiScanUtils(getContext()) {
            @Override
            public void processScanResult(List<ScanResult> results) {
                Map<String, Double> map = new HashMap<>();
                StringJoiner joiner = new StringJoiner("\n", "[", "]");
                for (ScanResult result : results) {
                    map.put(result.BSSID, (double) result.level);
                    joiner.add(result.BSSID + ", " + result.level + ", " + result.SSID + ";");
                }
                Message message = new Message();
                Bundle n = new Bundle();
                n.putString("scan_result", joiner.toString());
                message.what = SCAN_STATUS_SUCCESS;
                message.setData(n);
                sHandler.sendMessage(message);
                String json = JSON.toJSONString(map);
                RequestParams requestParams = new RequestParams();
                requestParams.addFormDataPart("rp_id", id);
                requestParams.addFormDataPart("wifi_data", json);
                Log.d(TAG, "processScanResult: "  + id + " " + json);
//                new Thread(() -> HttpRequest.post("http://47.101.186.100:9102/collector/uploadWifiData", requestParams, new BaseHttpRequestCallback<ApiResult>() {
//                    @Override
//                    public void onStart() {
//                        super.onStart();
//
//                    }
//
//                    @Override
//                    protected void onSuccess(ApiResult apiResult) {
//                        if (apiResult.getCode() == 200) {
//                            viewModel.addScanCount();
//                            sHandler.sendEmptyMessage(UPLOAD_DATA_SUCCESS);
//                        }
//                    }
//
//                    @Override
//                    public void onFinish() {
//                        super.onFinish();
//                    }
//                })).start();
                executorService.execute(() -> HttpRequest.post("http://47.101.186.100:9102/collector/uploadWifiData", requestParams, new BaseHttpRequestCallback<ApiResult>() {
                    @Override
                    public void onStart() {
                        super.onStart();

                    }

                    @Override
                    protected void onSuccess(ApiResult apiResult) {
                        if (apiResult.getCode() == 200) {
                            viewModel.addScanCount();
                            sHandler.sendEmptyMessage(UPLOAD_DATA_SUCCESS);
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }
                }));

//                OkHttpUtil.sendPostOkHttpRequest("http://47.101.186.100:9102/collector/uploaddata", params, new Callback() {
//                    @Override
//                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
//
//                    }
//
//                    @Override
//                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//
//                    }
//                });

            }
        };
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_collector, container, false);
    }

    public void initHandler() {
        sHandler = new Handler(Looper.myLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                switch (msg.what) {
                    case SCAN_STATUS_SUCCESS: {
                        Bundle data = msg.getData();
                        String scan_result = data.getString("scan_result");
                        textViewScanStatus.setText("扫描成功");
                        textViewResult.append("第" + (viewModel.getScanCount().getValue() + 1) + "扫描结果如下：\n");
                        textViewResult.append(scan_result + "\n");
                        break;
                    }
                    case STOP_SCAN_WIFI_CMD: {
                        textViewScanStatus.setText("已停止扫描");
                        break;
                    }
                    case SCAN_STATUS_FAILURE: {
                        textViewScanStatus.setText("扫描过于频繁...");
                        sHandler.sendEmptyMessageDelayed(WAITING_NEXT_SCAN, 3000);
                        break;
                    }
                    case UPLOAD_DATA_SUCCESS: {
                        textViewScanStatus.setText("扫描完成并成功上传数据！");
                        sHandler.sendEmptyMessageDelayed(WAITING_NEXT_SCAN, 5000);
                        break;
                    }
                    case WAITING_NEXT_SCAN: {
                        if (isScaning) {
                            textViewScanStatus.setText("正在等待下一次扫描...");

                        }
                    }
                    break;
                    default:
                        super.handleMessage(msg);
                        break;
                }
            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_start_scan: {
                if (!isScaning) {
                    textViewScanStatus.setText("正在开启扫描...");
                    initWifiScanner();
                    isScaning = true;
                    textViewResult.append("\n正在扫描...\n");
                } else {
                    textViewResult.append("\n已开始扫描，请耐心等待...\n");
                }
                break;
            }
            case R.id.btn_stop_scan: {
                if (isScaning) {
                    collectorWifiScanUtils.destroyed();
                    isScaning = false;
                    textViewResult.append("\n已停止扫描...\n");
                    sHandler.sendEmptyMessage(STOP_SCAN_WIFI_CMD);
                }
                break;
            }
            default:
                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        viewModel.clearScanCount();
        if (isScaning) {
            collectorWifiScanUtils.destroyed();
            isScaning = false;
        }
    }
}